package com.simple.mipc.messager;

import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import java.io.Closeable;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class MessengerMessage extends ConcurrentHashMap<String, Messenger> implements Closeable {

    private static MessengerMessage instance = new MessengerMessage();

    private MessengerMessage() {

    }

    public static MessengerMessage getInstance() {
        if (Objects.isNull(instance)) {
            instance = new MessengerMessage();
        }
        return instance;
    }

    public void register(String key, Messenger value) {
        put(key, value);
    }

    public Messenger unregister(String key) {
        return remove(key);
    }

    public Messenger lookup(String key) {
        return get(key);
    }

    public boolean sendMsg(String name, Message message, String key, String msg) {
        Messenger messenger = lookup(name);
        Bundle bundle = message.getData();
        bundle.putString(key, msg);
        try {
            messenger.send(message);
            return true;
        } catch (RemoteException e) {
            unregister(name);
            return false;
        }
    }

    @Override
    public void close() {
        clear();
    }
}
